package com.niit.chapter1;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 实现登录功能的逻辑
 * @author yaojianfeng
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ServletContext context;

    @Override
    public void init(ServletConfig config) {
        context = config.getServletContext();

    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //模拟从数据库获取账户密码
        String dbUsername =  context.getInitParameter("username");
        String dbPassword =  context.getInitParameter("password");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        //首先匹配用户名
        if (dbUsername.equals(username)) {
            //匹配密码
            if (dbPassword.equals(password)) {
                //匹配成功显示登录成功页面
                resp.sendRedirect(req.getContextPath()+"/Foodhub/LoginSuccess.html");
            } else {
                //匹配失败显示找回密码界面
                resp.sendRedirect(req.getContextPath()+"/Foodhub/LoginFail.html");
            }
        } else {
            //账号匹配失败 则显示注册页面
            resp.sendRedirect(req.getContextPath()+"/Foodhub/LoginFail.html");
            /*writer.println(
                    "<!DOCTYPE html>\n" +
                            "<html lang=\"en\">\n" +
                            "<head>\n" +
                            "    <meta charset=\"UTF-8\">\n" +
                            "</head>\n" +
                            "<body>\n" +
                            "<h1>此账号没有注册,请 <a href=\"/jeff/chapter3/register.html\">注册</a></h1>\n" +
                            "</body>\n" +
                            "</html>"
            );*/
        }
    }
}